<template>
  <el-cascader
    ref="cascaderRef"
    v-model="cascaderValue"
    :options="unitList"
    :props="cascaderProps"
    :disabled="disable"
    :placeholder="placeholder"
    @change="handleCascaderChange"
  />
</template>

<script setup lang="ts">
import { computed, nextTick, ref, useTemplateRef, watch } from 'vue'
import useUnitStore from '@/stores/unit'
import {
  CascaderInstance,
  CascaderNode,
  CascaderProps,
  CascaderValue,
  Resolve,
} from 'element-plus'
import { PageParam } from '@/type'
import { getUnitByLazy } from '@/api/sys/unit'
import { getAllUserByUnitIdAndCode } from '@/api/sys/userManage'
import { cloneDeep } from 'lodash-es'

const {
  disable = false,
  placeholder = '请选择',
  roleCode,
} = defineProps<{
  disable?: boolean
  placeholder?: string
  roleCode?: string
}>()

const emit = defineEmits(['change'])
const cascaderRef = useTemplateRef<CascaderInstance>('cascaderRef')
const model = defineModel()
const unitStore = useUnitStore()

const cascaderValue = ref(undefined)
const cascaderProps = ref<CascaderProps>({
  value: 'id',
  label: 'name',
  lazy: true,
  lazyLoad: handleLazyLoadCascader,
})

watch(
  () => model.value,
  (value) => {
    if (!value) {
      cascaderValue.value = undefined
    } else if (Array.isArray(value) && value.length === 3) {
      cascaderValue.value = [value[0], value[1], 'u-' + value[2]]
    }
  },
  {
    deep: true,
  },
)

const unitList = computed(() => {
  return unitStore.list.map((item) => {
    return {
      ...item,
      leaf: false,
    }
  })
})

async function handleLazyLoadCascader(node: CascaderNode, resolve: Resolve) {
  const postData: PageParam = {
    currentPage: 0,
    pageSize: 0,
    sort: [],
    query: {
      node: node.data.id,
    },
  }

  if (node.level === 1) {
    const { data } = await getUnitByLazy(postData)
    if (data.status === 200 && data.data.length !== 0) {
      resolve(
        data.data.map((item: any) => {
          return {
            id: item.id,
            name: item.unitForShort,
            leaf: false,
          }
        }) || [],
      )
    } else {
      resolve([])
    }
  } else if (node.level === 2) {
    const { data } = await getAllUserByUnitIdAndCode({
      departmentId: node.data.id as number,
      roleCode: roleCode,
    })
    if (data.status === 200 && data.data.length !== 0) {
      resolve(
        data.data.map((item: any) => {
          return {
            ...item,
            id: 'u-' + item.id,
            name: item.name,
            leaf: true,
          }
        }) || [],
      )
    } else {
      resolve([])
    }
  }
}

function handleCascaderChange(value: CascaderValue | undefined) {
  if (!value) {
    model.value = undefined
  } else if (Array.isArray(value) && value.length === 3) {
    if (typeof value[2] === 'string') {
      const value2 = Number(value[2].substring(2))
      model.value = [value[0], value[1], value2]
    } else {
      model.value = value
    }
  } else {
    model.value = value
  }
  nextTick(() => {
    emit('change', cloneDeep(model.value))
  })
}

defineExpose({ getCheckedNodes })

function getCheckedNodes(leafOnly: boolean) {
  return cascaderRef.value?.getCheckedNodes(leafOnly)
}
</script>

<style scoped lang="scss"></style>
